/*
 * 编辑材质
 * @Author: zfx
 * @Date: 2018-09-04 14:00:07
 */
<template>
	<div class="v-customer-material-edit">
		<Row
			type="flex"
			justify="start">

			<i-col push="1">
				<Form
					ref="formValidate"
					:model="formValidate"
					:rules="ruleValidate"
					:label-width="110"
					name="edit-form">

					<Form-item
						:label="$t('material_management.name')"
						prop="name">
						<i-input
							v-model="formValidate.name"
							:placeholder="$t('material_management.please_enter_material_name')"
							name="edit-name"
							type="text"/>
					</Form-item>

					<Form-item
						:label="$t('material_management.sort')"
						prop="sort">
						<InputNumber
							:max="100000"
							:min="0"
							v-model="formValidate.sort"
							:placeholder="$t('material_management.please_enter_priority')"/>
					</Form-item>

					<Form-item>
						<Button
							type="primary"
							@click="handleSubmit('formValidate')">
							{{ $t('common.update') }}
						</Button>
					</Form-item>
				</Form>
			</i-col>

		</Row>
	</div>
</template>

<script>

export default {
	name: 'MaterialEdit',
	props: {
		materialDetail: {
			type: Object,
			default() {
				return {};
			},
		},
	},

	data() {
		return {
			formValidate: {
				name: '', // 材质名称
				sort: 0, // 优先级
			}, // 更新材质时的表单

			ruleValidate: { // 表单验证规则
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('material_management.name') }),
						trigger: 'blur,change',
					},
				],
				sort: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('material_management.sort') }),
						trigger: 'blur,change',
					},
				],
			},
		};
	},

	created() {
		this.initFormData();
	},

	methods: {
		initFormData() {
			if (this.materialDetail && Object.keys(this.materialDetail).length > 0) {
				this.formValidate.name = this.materialDetail.name;
				this.formValidate.sort = this.materialDetail.sort;
			}
		},

		/**
         * 更新材质信息
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.formDataEdit();
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
         * 重置表单
         * @param  {string} name {表单上对应的ref值}
         * @return {undefined}
         */
		handleReset(name) {
			this.$refs[name].resetFields();
		},

		/**
         * 手动拼接表单数据
         * @return {Object} {拼接好的表单数据}
         */
		formDataEdit() {
			const new_object = {
				_method: 'PUT',

				name: this.formValidate.name,
				sort: this.formValidate.sort,
			};

			const form_data = new FormData();

			Object.keys(new_object).forEach((key) => {
				form_data.append(key, new_object[key]);
			});

			this.$emit('update', this.materialDetail.id, form_data);
		},

	},
};
</script>
